package com.ubivelox.uienginesample;


import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;


public class CubeRenderer implements Renderer {
	
	private Cube mCube;
	private float mCubeRotAngle = 0;
	private TextureLoader mTextureLoader;
	private int[] mTextures = new int[1];

	public interface TextureLoader{
		void loadTexture(GL10 gl);
	}
	
	public CubeRenderer(TextureLoader loader) {		
	    mTextureLoader = loader;
		mCube = new Cube(1, 1, 1);     
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer.
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
                GL10.GL_MODULATE);

		gl.glLoadIdentity(); 				
		gl.glTranslatef(0.0f, 0.0f, -10.0f);
		
		gl.glRotatef(-90.0f, 0.0f, 0.0f, 1.0f);		
		
		mTextureLoader.loadTexture(gl);
		
		gl.glPushMatrix();
		gl.glRotatef(mCubeRotAngle, 0.0f, 0.0f, 1.0f);
		mCube.draw(gl);
		gl.glPopMatrix();
		
		gl.glPushMatrix();
		gl.glTranslatef(3, 0, 0);
		mCube.draw(gl);
		gl.glPopMatrix();
		
		gl.glPushMatrix();
		gl.glTranslatef(-3, 0, 0);
		gl.glRotatef(mCubeRotAngle, 1.0f, 0.0f, 0.0f);
		mCube.draw(gl);
		gl.glPopMatrix();
		
		mCubeRotAngle += 2;
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
				100.0f);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();

	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
	    
        gl.glGenTextures(1, mTextures, 0);

        gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
        
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
		
		gl.glClearColor(0.3f, 0.3f, 0.3f, 0.6f);
		gl.glShadeModel(GL10.GL_SMOOTH);
		
		gl.glEnable(GL10.GL_TEXTURE_2D);
			
		gl.glClearDepthf(1.0f);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);

	}

}
